class StoreController < ApplicationController
  def index
    @products = Product.find_products_for_sale
		@count = increment_count
		@count_minimum_to_display = true if @count > 5
		@cart = find_cart

  end

	def add_to_cart
    product = Product.find(params[:id])
    rescue ActiveRecord::RecordNotFound
		logger.error("Attempt to access invalid product #{params[:id]}" )
		redirect_to_index("Invalid product")
	else
		@cart = find_cart
    @current_item = @cart.add_product(product)
		session[:counter] = 0
		if request.xhr?
			respond_to { |format| format.js }
		else
			redirect_to_index
		end
  end

	def empty_cart
		session[:cart] = nil
		session[:counter] = 0
		redirect_to_index
	end
	
private
	def redirect_to_index(msg = nil)
		flash[:notice] = msg if msg
		redirect_to :action => :index
	end

	def find_cart
    session[:cart] ||= Cart.new
  end

	def increment_count
  session[:counter] ||= 0
  session[:counter] += 1
end

	
end

